import { Input, message, Modal } from 'antd';
import Form, { FormInstance } from 'antd/lib/form';
import FormItem from 'antd/lib/form/FormItem';
import React from 'react';
import { addRole, modifyRole } from 'admin/servers/servers';
import '../style.scss';

interface RoleOperationProp {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

interface RoleOperationState extends RoleOperationProp {
  mode: 'create' | 'modify';
  visible: boolean;
  roleId: number;
}

interface RoleFormData {
  roleName: string;
  roleId?: number;
  roleDesc: string;
}

export class RoleOperation extends React.Component<RoleOperationProp, RoleOperationState> {
  private formRef: React.RefObject<FormInstance>;

  private roleInfo: RoleFormData;

  constructor(prop: RoleOperationState) {
    super(prop);
    this.roleInfo = {} as RoleFormData;
    this.formRef = React.createRef();
    this.state = {
      ...prop,
      mode: 'create',
      visible: false,
      roleId: 0,
    };
  }

  public open(mode: 'create' | 'modify', data?: RoleFormData): void {
    this.setState({
      mode: mode,
      visible: true,
    });
    if (data) {
      this.roleInfo = data;
      setTimeout(() => {
        this.formRef.current?.setFieldsValue(data);
      }, 0);
    }
  }

  public close(): void {
    this.setState({
      visible: false,
    });
    const form = this.formRef.current;
    form?.resetFields();
    form?.setFieldsValue({});
  }

  private submitData(): void {
    const apiMap = {
      create: addRole,
      modify: modifyRole,
    };
    const mode = this.state.mode;
    const api = apiMap[mode] as any;
    const form = this.formRef.current;
    form
      ?.validateFields()
      .then(res => {
        const params = form.getFieldsValue();
        mode === 'modify' && (params.roleId = this.roleInfo.roleId);
        if (res) {
          api(params).then((res: any) => {
            if (mode === 'create') {
              message.success('新建成功');
              this.state.callback();
            } else {
              message.success('编辑成功');
              this.state.callback(this.roleInfo.roleId);
            }
            this.close();
          });
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  render() {
    const { visible, mode } = this.state;

    return (
      <>
        <Modal
          className="role-operation-modal"
          title={mode === 'create' ? '新建角色' : '编辑角色'}
          onCancel={() => {
            this.close();
          }}
          onOk={() => {
            this.submitData();
          }}
          visible={visible}
        >
          <Form layout="horizontal" ref={this.formRef}>
            <FormItem
              label="角色名称"
              name="roleName"
              rules={[{ required: true, message: '请输入10位内字符' }]}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input maxLength={10} placeholder="请输入10位内字符" />
            </FormItem>
            <FormItem label="角色描述" name="roleDesc">
              <Input.TextArea />
            </FormItem>
          </Form>
        </Modal>
      </>
    );
  }
}
